package com.sx.wechat.config;

import com.jagregory.shiro.freemarker.ShiroTags;
import com.sx.core.mybatis.PaginationInterceptor;
import com.sx.core.mybatis.SessionTemplate;
import com.sx.core.spring.FreeMarkerVariable;
import com.sx.wechat.security.Oauth2Interceptor;
import com.sx.wechat.shiro.InformationInterceptor;
import freemarker.template.TemplateModelException;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.AdviceMode;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.core.Ordered;
import org.springframework.core.env.Environment;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.method.support.HandlerMethodReturnValueHandler;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Configuration
@EnableAspectJAutoProxy
@EnableTransactionManagement(mode = AdviceMode.PROXY, proxyTargetClass = false, order = Ordered.LOWEST_PRECEDENCE)
@EnableCaching
public class WechatFilterConfig implements WebMvcConfigurer {

    @Autowired
    private Environment env;

    private CorsConfiguration buildConfig() {
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.addAllowedOrigin("*"); // 1允许任何域名使用
        corsConfiguration.addAllowedHeader("*"); // 2允许任何头
        corsConfiguration.addAllowedMethod("*"); // 3允许任何方法（post、get等）
        return corsConfiguration;
    }

    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
//        source.registerCorsConfiguration("/api/**", buildConfig()); // 4
        source.registerCorsConfiguration("/**", buildConfig()); // 4
        return new CorsFilter(source);
    }
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/").setViewName("redirect:/login");
        registry.setOrder(Ordered.HIGHEST_PRECEDENCE);

    }
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 拦截规则
        registry.addInterceptor(new Oauth2Interceptor()).addPathPatterns("/api/**");
        if(env.getProperty("spring.profiles.active").equals("dev")){
            registry.addInterceptor(new InformationInterceptor()).addPathPatterns("/tc/**");
        }

    }



    @Bean("paginationInterceptor")
    public PaginationInterceptor paginationInterceptor() {
        PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
        return paginationInterceptor;
    }
    @Bean("executor")
    public ThreadPoolTaskExecutor executor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(4);
        executor.setMaxPoolSize(50);
        return executor;
    }

    @Bean
    public NamedParameterJdbcTemplate namedParameterJdbcTemplate(DataSource dataSource){
        return new NamedParameterJdbcTemplate(dataSource);
    }

    @Bean
    public SessionTemplate sessionTemplate(SqlSessionFactory sqlSessionFactory) {
        PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
        sqlSessionFactory.getConfiguration().addInterceptor(paginationInterceptor);
        return new SessionTemplate(sqlSessionFactory);
    }
    @Bean
    public FreeMarkerVariable freeMarkerVariable(FreeMarkerConfigurer configurer)  {
        Map<String,Object> freemarkerVariables=new HashMap<>();
        freemarkerVariables.putAll(freemarkerVariables());
        try {
            freemarker.template.Configuration config=configurer.getConfiguration();
            config.setSharedVaribles(freemarkerVariables);
            config.setSharedVariable("shiro", new ShiroTags());
        } catch (TemplateModelException e) {
        }
        return new FreeMarkerVariable();
    }
    public  Map<String, Object> freemarkerVariables(){
        return new HashMap<>();
    };



}